<script setup>
import { ref, nextTick } from 'vue'
import ChannelSelect from '@/views/article/components/ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { artAddService, artUpdateService, artDetailService } from '@/api/article'
import {baseURL} from '@/utils/request'

const visibleDrawer = ref(false)
const defaultFormModel = {
  title: '',
  cate_id: '',
  cover_img:'',
  content: '',
  state: ''
}
const formModel = ref({...defaultFormModel})

const imageUrl = ref('')
const onSelectFile = (uploadFile) => {
  formModel.value.cover_img = uploadFile.raw
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  console.log(uploadFile.raw)
}

const emit = defineEmits(['getArticleList'])
const onSubmit = async (stata) => {
  formModel.value.state = stata
  const fd = new FormData()
  for (let item in formModel.value) {
    fd.append(item, formModel.value[item])
  }
  if(formModel.value.id){
    await artUpdateService(fd)
    ElMessage.success('编辑文章成功')
    visibleDrawer.value = false
    formModel.value = {...defaultFormModel}
    emit('getArticleList')
  }else{
    await artAddService(fd)
    ElMessage.success('添加文章成功')
    visibleDrawer.value = false
    formModel.value = {...defaultFormModel}
    emit('getArticleList')
  }
}

const editorRef = ref('')

const open =async (row) => {
  visibleDrawer.value = true
  if(row.id){
    const {data:{data}} = await artDetailService(row.id)
    formModel.value = { ...data }
    // 构建完整图片URL
    const fullImageUrl = baseURL + data.cover_img
    imageUrl.value = fullImageUrl

    // 将网络图片URL转换为File对象，以便可以重新上传
    try {
      const file = await urlToFile(fullImageUrl)
      if (file) {
        formModel.value.cover_img = file
      }
    } catch (error) {
      console.error('转换图片失败:', error)
      // 即使转换失败，也继续执行，因为imageUrl已经设置好了，可以正常显示
    }
  }else{
    imageUrl.value = ''
    formModel.value = {...defaultFormModel}
    await nextTick()
    editorRef.value.setHTML('')
  }
}

const rules = ref({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' }
  ],
  cate_id: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  cover_img: [
    { required: true, message: '请上传文章封面', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  state: [
    { required: true, message: '请选择文章状态', trigger: 'change' }
  ]
})

defineExpose({
  open
})


const urlToFile = async (url, filename = 'image.jpg', mimeType = 'image/jpeg') => {
  try {
    // 发送请求获取图片数据
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`无法加载图片: ${response.status}`);
    }

    // 将响应转换为Blob
    const blob = await response.blob();

    // 从URL推断文件扩展名和MIME类型
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    const extension = pathname.split('.').pop().toLowerCase();

    // 根据扩展名设置正确的MIME类型
    const mimeTypes = {
      'jpg': 'image/jpeg',
      'jpeg': 'image/jpeg',
      'png': 'image/png',
      'gif': 'image/gif',
      'webp': 'image/webp'
    };

    const actualMimeType = mimeTypes[extension] || mimeType;
    const actualFilename = `image.${extension}`;

    // 创建File对象
    return new File([blob], actualFilename, { type: actualMimeType });
  } catch (error) {
    console.error('URL转File失败:', error);
    ElMessage.error('图片加载失败');
    return null;
  }
}
</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
  <el-form :model="formModel" ref="formRef" label-width="100px" :rules="rules">
    <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
    </el-form-item>
    <el-form-item label="文章分类" prop="cate_id">
      <channel-select
        v-model="formModel.cate_id"
        width="100%">
      </channel-select>
    </el-form-item>
    <el-form-item label="文章封面" prop="cover_img">
      <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="onSelectFile"
        >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <QuillEditor theme="snow"
          v-model:content="formModel.content"
          content-type="html"
          ref="editorRef"/>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('已发布')">发布</el-button>
        <el-button type="info" @click="onSubmit('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
